package com.kun.index.controller;


import com.kun.common.Constants;
import com.kun.common.ResultDto;
import com.kun.common.annotation.PermissionAuthentication;
import com.kun.index.entity.Blog;
import com.kun.index.entity.Label;
import com.kun.index.service.LabelService;
import com.kun.index.service.impl.BlogLabelServiceImpl;
import com.kun.index.service.impl.LabelServiceImpl;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 标签表 前端控制器
 * </p>
 *
 * @author kunkun
 * @since 2024-03-18
 */
@RestController
@RequestMapping("/index/label")
public class LabelController {

    @Autowired
    private LabelServiceImpl labelService;

    @Autowired
    private BlogLabelServiceImpl blogLabelService;

    @GetMapping("/queryAllLabels")
    @ApiOperation("查询所有的标签")
    public ResultDto queryAllLabels(@RequestParam(required = false,name = "id")Integer id) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("id",id);
        List<Label> labels= labelService.queryLabels(map);

        if (labels.size()>0){
            return ResultDto.success(labels);
        }else {
            return ResultDto.fail(Constants.CODE_301,"数据为空");
        }
    }

    @PostMapping("/addLabel")
    @ApiOperation("新增标签")
    public ResultDto addLabel(@RequestBody Label label) {

        Integer id = labelService.addLabel(label);

        if (id>0){
            return ResultDto.success(id);
        }else {
            return ResultDto.fail("新增标签失败");
        }
    }

    @PostMapping("/updateLabel")
    @ApiOperation("编辑标签")
    public ResultDto updateLabel(@RequestBody Label label) {

        Integer id = labelService.updateLabel(label);

        if (id>0){
            return ResultDto.success(id);
        }else {
            return ResultDto.fail("编辑标签失败");
        }
    }


    @PostMapping("/deleteLabel")
    @ApiOperation("删除标签")
    public ResultDto deleteLabel(@RequestBody Label label){
        int num = labelService.deleteLabel(label);
        //删除标签之后，要把相关的BlogLabel删除
        blogLabelService.deleteBlogLabel(label.getId());
        if (num>0){
            return ResultDto.success("删除博客成功");
        }else{
            return ResultDto.fail("删除博客失败");
        }


    }
    @PostMapping("/batchDeleteLabel")
    @ApiOperation("批量删除标签")
    public ResultDto batchDeleteLabel(@RequestBody List<Integer> ids){
        int num = labelService.batchDeleteLabel(ids);
        //删除标签之后，要把相关的BlogLabel删除
        for (Integer labelId : ids) {
            blogLabelService.deleteBlogLabel(labelId);
        }
        if (num>0){
            return ResultDto.success("删除博客成功");
        }else{
            return ResultDto.fail("删除博客失败");
        }


    }


}

